package com.affectu.category;

import java.util.ArrayList;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;

import com.affectu.dao.DAOBase;
import com.affectu.task.Task;

/**
 * 2008-8-19
 * 
 * @author daniel nathan
 */
@Name("categoryAction")
public class CategoryAction extends DAOBase {

	@In(required = false)
	@Out(required = false)
	public Task task;

	public List<Category> roots;

	@SuppressWarnings("unchecked")
	public List<Category> getRoots() {
		List list = em.createQuery("from Category c where c.level=0").list();
		if (list.size() == 0) {
			Category root = new Category();
			root.setName("root");
			root.setLevel(0);
			em.persist(root);
		}
		this.roots = em.createQuery("from Category c where c.level=0").list();
		return roots;
	}

	@Factory(value = "categoryAction_oneLevelCategory", scope = ScopeType.PAGE)
	public List<Category> getOneLevelCategory() {
		return this.getCategoriesByLevel(1);
	}

	@SuppressWarnings("unchecked")
	public List<Category> getCategoriesByLevel(int level) {
		List list = new ArrayList();
		try {
			list = em.createQuery("from Category c where c.level=:level")
					.setInteger("level", level).list();

		} catch (Exception ex) {
			this.logException(ex);
		}
		return list;
	}

	public String sendParentNode(Category parent) {
		this.getSessionScope().put("parentNode", parent);
		return "";
	}

	public String addChildNode(Category child) {
		try {
			Category parent = (Category) this.getSessionScope().get(
					"parentNode");
			child.setParent(parent);
			child.setLevel(parent.getLevel() + 1);
			em.persist(child);
		} catch (Exception ex) {
			this.logException(ex);
		}
		return "ok";
	}

	public String addChildCategory(Category child, Category current) {
		child.setParent(current);
		child.setLevel(current.getLevel() + 1);
		em.persist(child);
		return "";
	}

	public String modifyCategory(Category node) {
		try {
			em.merge(node);
		} catch (Exception ex) {
			this.logAffectuException(ex, "");
		}
		return "";
	}

	public String deleteCategory(Category node) {
		try {
			em.delete(node);
		} catch (Exception ex) {
			this.logAffectuException(ex, "");
		}
		return "";
	}
}
